package icu.zhhll.beans;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

/**
 * 获取bean
 *
 * @author zh
 * @date 2023/8/13 22:01
 */
@Component
public class Springs implements ApplicationContextAware {


    private static ApplicationContext context;

    public static ApplicationContext getApplicationContext() {
        return context;
    }

    @Autowired
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (context == null) {
            context = applicationContext;
        }
    }

    public static <T> T getBean(Class<? extends T> beanClass, String beanName) {
        assertContextNotNull();
        return getApplicationContext().getBean(beanName, beanClass);
    }

    public static Object getBean(String beanName) {
        assertContextNotNull();
        return getApplicationContext().getBean(beanName);
    }

    public static <T> T getBean(Class<? extends T> beanClass) {
        assertContextNotNull();
        return getApplicationContext().getBean(beanClass);
    }

    private static void assertContextNotNull() {
        Assert.notNull(getApplicationContext(), "The spring applicationContext was not initialized");
    }
}
